package com.jf3q.front.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jf3q.common.domain.EduMember;
import com.jf3q.common.domain.EduTeacher;
import com.jf3q.common.mapper.EduTeacherMapper;
import com.jf3q.common.utils.JwtTokenUtil;
import com.jf3q.common.utils.OssUtils;
import com.jf3q.common.utils.SaltPassUtils;
import com.jf3q.common.vo.ResultVo;
import com.jf3q.front.dto.MemberLoginDto;
import com.jf3q.front.dto.MemberRegDto;
import com.jf3q.front.dto.PassWordDto;
import com.jf3q.front.service.MemberService;
import com.jf3q.front.vo.LoginSuccessVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Base64;

@RestController
@RequestMapping("/member")
@Tag(name = "会员控制层")
public class MemberController {
    @Autowired
    MemberService memberService;
    @Autowired
    JwtTokenUtil jwtTokenUtil;
    @Autowired
    OssUtils ossUtils;

    @PostMapping("/reg")
    @Operation(summary = "会员注册")
    public ResultVo reg(@RequestBody MemberRegDto memberRegDto){

        //校验各种
        memberService.reg(memberRegDto);
        return ResultVo.success();

    }

    @PostMapping("/uploadAvatar")
    @Operation(summary = "上传头像")
    public ResultVo uploadAvatar(MultipartFile file){
        return ResultVo.success("上传成功",ossUtils.upload("member",file));

    }

    @PostMapping("/updatePass")
    @Operation(summary = "修改密码")
    public ResultVo updatePass(@RequestBody PassWordDto passwordDto, HttpServletRequest request){
        if (!StringUtils.hasText(passwordDto.getOldPass())) {
            return ResultVo.error("旧密码必填");
        }
        if (!StringUtils.hasText(passwordDto.getNewPass())) {
            return ResultVo.error("新密码必填");
        }
        if (!StringUtils.hasText(passwordDto.getRePass())) {
            return ResultVo.error("确认密码必填");
        }
        if (!passwordDto.getRePass().equals(passwordDto.getNewPass())) {
            return ResultVo.error("新密码和确认密码不一致");
        }
        String token = request.getHeader("token");
        if (!StringUtils.hasText(token)) {
            return ResultVo.error("token必传");
        }
        //判断旧的密码输入是否正确
        EduMember member = memberService.getById(jwtTokenUtil.getUserIdByToken(token));
        if (!SaltPassUtils.PasswordValidation(member.getSalt(),passwordDto.getOldPass(),member.getPassword())) {
            return ResultVo.error("旧密码不正确");
        }

        //修改密码

        member.setPassword(SaltPassUtils.hashPassword(passwordDto.getNewPass(), Base64.getDecoder().decode(member.getSalt())));
        memberService.saveOrUpdate(member);
        return ResultVo.success();

    }

    @PostMapping("/saveOrUpdate")
    @Operation(summary = "修改个人信息")
    public ResultVo updateInfo(@RequestBody EduMember member){

        try {
            memberService.saveOrUpdate(member);
            EduMember byId = memberService.getById(member.getId());
            byId.setPassword(null);
            byId.setSalt(null);
            return ResultVo.success(byId);
        } catch (Exception e) {
            throw new RuntimeException("操作异常");
        }

    }


    @PostMapping("/login")
    @Operation(summary = "会员登陆")
    public ResultVo login(@RequestBody MemberLoginDto memberLoginDto){

        //.trim()把空格去掉
        if (StringUtils.isEmpty(memberLoginDto.getMobile().trim())) {
            return ResultVo.error("手机号必填");
        }else if (StringUtils.isEmpty(memberLoginDto.getPassword())) {
            return ResultVo.error("密码必填");
        }else{
            LambdaQueryWrapper<EduMember> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(EduMember::getMobile, memberLoginDto.getMobile());
            EduMember member = memberService.getOne(queryWrapper);
            if(ObjectUtils.isEmpty(member)){
                return ResultVo.error("账号不存在");
            }
            if(member.getIsDisabled()){
                return ResultVo.error("账号已被禁用");
            }

            //校验密码是否正确（这里做了加盐加密）
            if (!SaltPassUtils.PasswordValidation(member.getSalt(),memberLoginDto.getPassword(),member.getPassword())) {
                return ResultVo.error("密码错误");
            }

            //生成token返回给前端
            String token = jwtTokenUtil.getToken(member.getMobile(),member.getId());

            //把token和个人基本信息返回给前端
            //把敏感信息置空
            member.setPassword(null);
            member.setSalt(null);
            return ResultVo.success( new LoginSuccessVo(token,member));

        }


    }


}
